<template>
  <view class="container">
    <ve-form style="padding: 24rpx" :model="form" ref="feeFormRef" :rules="rules">
      <ve-card :customContentStyle="{ paddingBottom: 0 }">
        <ve-form-item label="合同类型" class="memeber-type-form">
          <ve-radio v-model="form.contractType" :list="contractTypeEnum" disabled />
        </ve-form-item>
      </ve-card>
      <view class="alert-content">
        <view class="alert-item">
          <image src="../../../static/images/alert_icon.png" mode="widthFix"></image>
          <text>
            如修改了对应的字段信息，将使用最新的信息更新电子合同中的内容，不影响订单的信息。请确保修改后的内容与实际订单的内容保持一致，避免发生合同内容的纠纷。
          </text>
        </view>
      </view>
      <ve-card title="客户信息" :customContentStyle="{ paddingBottom: 0 }">
        <ve-form-item label="客户类型" class="memeber-type-form">
          <ve-radio v-model="form.memberType" :list="dict.memberTypeEnum" disabled />
        </ve-form-item>
        <ve-form-item label="承租人">
          <ve-input v-model="form.memberName" disabled />
        </ve-form-item>
        <ve-form-item label="联系电话">
          <ve-input v-model="form.memberPhone" disabled />
        </ve-form-item>
        <ve-form-item label="证件类型">
          <ve-radio v-model="form.cardType" :list="dict.cardTypeEnum" @confirm="radioconfirm" />
        </ve-form-item>
        <ve-form-item label="证件号">
          <ve-input v-model="form.cardNumber" :maxlength="18" />
        </ve-form-item>
        <ve-form-item label="紧急联系人">
          <ve-input v-model="form.emergencyContactName" />
        </ve-form-item>
        <ve-form-item label="紧急联系人手机号" :borderBottom="false">
          <ve-input v-model="form.emergencyContactPhone" />
        </ve-form-item>
      </ve-card>
      <ve-card title="租赁信息" :customContentStyle="{ paddingBottom: 0 }">
        <!-- 选择短租租赁周期 -->
        <ve-form-item
          labelPosition="top"
          prop="timeRange"
          v-if="form.orderType == 1"
          required
          :label="form.contractType == 1 ? '预计租赁周期' : '预计续租周期'"
          :labelTooltipContent="form.contractType == 1 ? '租赁周期最小时间范围为1小时' : '续租周期最小时间范围为1小时'"
        >
          <template #label-extra>
            <view style="color: #3072f6"> 租期：{{ form.rentDays || '-' }} </view>
          </template>
          <ve-daterange-picker
            v-model:start="form.startTime"
            v-model:end="form.endTime"
            :placeholder="['开始时间', '结束时间']"
            mode="datetime"
            @confirm="timeRangeConfirmFn"
          />
        </ve-form-item>
        <!-- 选择长租租赁周期 -->
        <ve-form-item
          v-else
          labelPosition="top"
          prop="timeRange"
          required
          :label="form.contractType == 1 ? '预计租赁周期' : '预计续租周期'"
          :labelTooltipContent="form.contractType == 1 ? '租赁周期最小时间范围为1个月' : '续租周期最小时间范围为1个月'"
          :borderBottom="false"
        >
          <template #label-extra>
            <view style="color: #3072f6">
              租期：{{ form.rentDays ? form.rentDays.replace('月', ' 月 ').replace('天', ' 天') : '- 天' }}
            </view>
          </template>
          <view class="time-range-wrap">
            <view class="quick-date-list">
              <view
                class="quick-date-item"
                :class="{ active: item.active }"
                v-for="(item, index) in quickDateList"
                :key="index"
                @click="quickDateItemClicked(item)"
                >{{ item.label }}</view
              >
            </view>
            <ve-daterange-picker
              v-model:start="form.startTime"
              v-model:end="form.endTime"
              :config="{
                start: {
                  valueFormat: 'YYYY-MM-DD 00:00:00',
                },
                end: {
                  valueFormat: 'YYYY-MM-DD 23:59:59',
                },
              }"
              :placeholder="['开始时间', '结束时间']"
              mode="date"
              @confirm="timeRangeConfirmFn"
            />
          </view>
        </ve-form-item>
        <!-- 取车门店 -->
        <LeaseSite type="site" ref="siteRef" :siteRequired="true" :orderType="form.orderType" />
        <!-- 还车门店 -->
        <LeaseSite type="returnSite" ref="returnSiteRef" :orderType="form.orderType" />
      </ve-card>
      <ve-card title="车辆信息" :customContentStyle="{ paddingBottom: 0 }">
        <ve-form-item label="车辆来源" class="car-origin" required>
          <ve-radio v-model="form.carSource" :list="dict.carSourceEnum" @confirm="changeCarSourceFn" />
        </ve-form-item>
        <ve-form-item label="车牌号" prop="carId" required labelTooltipContent="请先选择租赁周期和取车门店后，再选择排车车辆">
          <CustomSelect tip="请先选择租赁周期和取车门店后，再选择排车车辆" @click="customSelectTap" :modelValue="form.carLicenseNo" />
        </ve-form-item>
        <ve-form-item label="排车车型" labelPosition="top" :borderBottom="false">
          <view class="platoon-model">{{ form.carModelName || '-' }}</view>
        </ve-form-item>
        <ve-form-item label="交车里程" v-if="form.isExistenceStartCarMileageFlag">
          <ve-input-number :precision="0" v-model="form.startCarMileageContract" />
        </ve-form-item>
        <ve-form-item label="交车油(电)量" :borderBottom="false" v-if="form.isExistenceStartCarOilFlag">
          <ve-input v-model="form.startCarOilContract" :maxlength="20" />
        </ve-form-item>
      </ve-card>
      <ve-card title="费用信息" :customContentStyle="{ paddingBottom: 0 }" v-if="form.contractFee && form.contractFee.length > 0">
        <ve-form-item
          v-for="(item, index) in form.contractFee"
          :key="index"
          :label="item.name"
          unit="元"
          required
          :prop="`contractFee.${index}.value`"
          :borderBottom="form.contractFee?.length - 1 == index ? false : true"
        >
          <ve-input-number placeholder="请输入" v-model="item.value" :min="0" :max="99999999.99" />
          <!-- <ve-input placeholder="请输入" v-model="item.value" :min="0" :max="99999999.99" /> -->
        </ve-form-item>
      </ve-card>
    </ve-form>

    <!-- 底部 footer -->
    <ve-bottom-box id="footer-box">
      <ve-button type="plain" @click="close">关闭</ve-button>
      <ve-button type="primary" size="long" :loading="okLoading" @click="submitFn">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>
<script setup>
  import { ref, computed, provide, watch, h } from 'vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { usePageDict } from '@/hooks/useDict'
  import LeaseSite from './components/lease-site.vue'
  import CustomSelect from './components/custom-select.vue'
  import { getContractDataAPI, updateFreeContractAPI, computeLongRentDayAPI } from '@/api/order/contract'
  import { computeRentDayAPI } from '@/api/order/sOrder'
  import { calcDateAPI } from '@/api/order/lOrder'
  import dayjs from 'dayjs'
  import useFormFold from '@/hooks/useFormFold'
  const { foldValidate } = useFormFold([])
  const dict = usePageDict('shortOrderDict')

  const defaultStartTime = dayjs().format('YYYY-MM-DD HH:mm:00')

  const form = ref({
    // 默认开始时间 开始
    timeRange: [defaultStartTime],
    startTime: defaultStartTime,
    // 默认开始时间 结束
    sendServiceFlag: 0,
    returnServiceFlag: 0,
    contractFee: [],
  })
  provide('contractForm', form)
  provide('contractInfo', form)

  // 租赁租赁周期限制
  const timeRangeValidator = (rule, value, callback) => {
    if (form.value.orderType == 1) {
      if (value) {
        let start = value[0]
        let end = value[1]
        if (start && end) {
          let diff = dayjs(end).diff(dayjs(start))
          if (diff < 60 * 60 * 1000) {
            callback(`${form.value.contractType == 1 ? '租赁' : '续租'}周期最小时间范围为1小时`)
          }
        }
      }
      callback()
    } else {
      if (value) {
        let start = value[0]
        let end = value[1]
        if (start && end) {
          let months = form.value.leaseMonths
          if (months == 0) {
            callback(`${form.value.contractType == 1 ? '租赁' : '续租'}周期最小时间范围为1个月`)
          }
        }
      }
      callback()
    }
  }

  const quickDateList = ref([
    { label: '一个月', active: false },
    { label: '三个月', active: false },
    { label: '半年', active: false },
    { label: '一年', active: false },
    { label: '两年', active: false },
  ])

  const quickDateItemClicked = (clickItem) => {
    const param = {
      startDateTime: dayjs().format('YYYY-MM-DD 00:00:00'),
    }
    switch (clickItem.label) {
      case '一个月':
        param.addMonths = 1
        break
      case '三个月':
        param.addMonths = 3
        break
      case '半年':
        param.addMonths = 6
        break
      case '一年':
        param.addYears = 1
        break
      case '两年':
        param.addYears = 2
        break
    }
    calcDateAPI(param).then((res) => {
      let startStr = param.startDateTime
      let endStr = res.result
      form.value.startTime = startStr
      form.value.endTime = endStr
      form.value.timeRange = [startStr, endStr]
      timeRangeConfirmFn(form.value.timeRange)
      quickDateList.value.forEach((item) => {
        if (item.label == clickItem.label) {
          item.active = true
        } else {
          item.active = false
        }
      })
    })
  }
  // 表单规则
  const rules = computed(() => {
    const contractRule = {
      cardNumber: { match: /^[a-zA-Z0-9]+$/, message: '支持数字、英文' },
      emergencyContactPhone: { len: 11, match: /^[0-9]+$/, message: '请输入正确格式的紧急联系人手机号' },
      siteId: { required: true, message: '请选择取车门店' },
      carSource: { required: true, message: '请选择车辆来源' },
      carId: { required: true, message: '请选择车辆' },
      timeRange: [{ required: true, message: '请选择预计租赁周期' }, { validator: timeRangeValidator }],
    }
    form.value.contractFee.forEach((item, index) => {
      contractRule[`contractFee.${index}.value`] = {
        required: true,
        message: '请输入',
      }
    })
    return contractRule
  })
  // 合同类型
  const contractType = ref(1)

  const contractId = ref('')

  const contractTypeEnum = [
    {
      label: '租车合同',
      value: 1,
    },
    {
      label: '续租合同',
      value: 2,
    },
  ]
  const radioconfirm = () => {
    form.value.cardNumber = null
  }
  // 日期范围变化，并计算租期
  const timeRangeConfirmFn = (value = []) => {
    if (form.value.orderType == 1) {
      form.value.timeRange = value
      // 计算租期
      if (value[0] && value[1]) {
        const param = {
          startTime: value[0],
          endTime: value[1],
          siteId: form.value.siteId,
        }
        computeRentDayAPI(param).then((res) => {
          let { days } = res.result
          if (days.indexOf('小时') >= 0 && days.indexOf('天') >= 0) {
            days = days.replace('天', ' 天 ').replace('小时', ' 小时')
          } else {
            days = days.replace('天', ' 天').replace('小时', ' 小时')
          }
          form.value.rentDays = days
        })
      }
    } else {
      // 清空选中
      quickDateList.value.forEach((item) => {
        item.active = false
      })
      form.value.timeRange = value
      // 计算租期
      if (value[0] && value[1]) {
        const param = {
          expectedUseCarTime: value[0],
          expectedReturnCarTime: value[1],
        }
        computeLongRentDayAPI(param).then((res) => {
          let result = res.result
          let dateStr = result.dateStr
          form.value.rentDays = dateStr
        })
      }
    }
  }
  // 编辑场景下，更新 ShortsiteConfig
  // const siteRef = ref()
  // const returnSiteRef = ref()
  // const updateShortsiteConfig = (siteId, siteName, type) => {
  //   if (type == 'site') {
  //     siteRef.value ? siteRef.value.changeSiteIdFn(siteId, { siteName }) : ''
  //   }
  //   if (type == 'returnSite') {
  //     returnSiteRef.value ? returnSiteRef.value.changeSiteIdFn(siteId, { siteName }) : ''
  //   }
  // }
  // 切换了门店、车型 清空排车页面的筛选条件
  watch([() => form.value.carSource, () => form.value.siteId, () => form.value.carModelId], () => {
    platoonModelQueryParam.value = {}
  })

  // 更换车辆来源
  const changeCarSourceFn = () => {
    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelName = undefined
    form.value.carModelId = undefined
  }
  const _param = (obj) => {
    let str = ''
    if (typeof obj == 'object') {
      for (let i in obj) {
        if (obj[i] == undefined) {
          continue
        }
        str += i + '=' + obj[i] + '&'
      }
    }
    return str.replace(/&$/g, '')
  }
  // 点击车牌选择事件
  const customSelectTap = () => {
    // 跳转选择车牌号页面
    let orderInfo = {
      // 当前选中的车辆 id
      carId: form.value.carId,
      siteId: form.value.siteId,
      siteName: form.value.siteName,
      modelId: form.value.carModelId,
      modelName: form.value.carModelName,
      startTime: form.value.startTime,
      endTime: form.value.endTime,
      rentDays: form.value.rentDays,
      carSource: form.value.carSource,
      // 订单来源
      orderSourceName: form.value.orderSourceName || orderSourceName.value,
    }
    if (form.value.orderType == 2) {
      orderInfo.orderStatus = 10
    }
    let paramStr = _param({
      mode: 'select',
      type: form.value.orderType == 1 ? 'short-order' : 'long-order',
      data_json: JSON.stringify({
        ...orderInfo,
        ...platoonModelQueryParam.value,
      }),
      orderInfo_json: JSON.stringify(orderInfo),
    })
    uni.navigateTo({
      url: `/pages/asset/stock/car-stock/selector?${paramStr}`,
    })
  }
  // 选择车牌完成后，函数暴露到上级
  const platoonModelQueryParam = ref({})
  const close = () => {
    uni.navigateBack()
  }
  const okLoading = ref(false)
  const feeFormRef = ref()

  const submitFn = () => {
    okLoading.value = true
    feeFormRef.value.validate((valid, errors) => {
      if (!valid) {
        // 页面滚动到错误位置
        foldValidate(errors, true)
        okLoading.value = false
      } else {
        let formValue = form.value
        let params = {
          id: formValue.id,
          cardType: formValue.cardType,
          cardNumber: formValue.cardNumber,
          emergencyContactName: formValue.emergencyContactName,
          emergencyContactPhone: formValue.emergencyContactPhone,
          startTime: formValue.startTime,
          endTime: formValue.endTime,
          rentDays: formValue.rentDays,
          siteId: formValue.siteId,
          siteName: formValue.siteName,
          returnServiceFlag: formValue.returnServiceFlag,
          sendServiceFlag: formValue.returnServiceFlag,
          returnSiteId: formValue.returnSiteId,
          returnSiteName: formValue.returnSiteName,
          address: formValue.address,
          returnAddress: formValue.returnAddress,
          carSource: formValue.carSource,
          carId: formValue.carId,
          carLicenseNo: formValue.carLicenseNo,
          carModelName: formValue.carModelName,
          contractFee: formValue.contractFee,
          startCarMileageContract: formValue.startCarMileageContract,
          startCarOilContract: formValue.startCarOilContract,
        }
        if (formValue.emergencyContactPhone == '') {
          params.emergencyContactPhone == null
        }
        updateFreeContractAPI(params)
          .then((res) => {
            okLoading.value = false
            if (res.result?.resultErrorCode == 9999) {
              uni.showToast({
                title: h('view', {}, [
                  h('text', {}, `请先上传${res.result.templateName}${res.result.templateTypeName}模板的`),
                  h('text', { style: 'color: red' }, '公司印章'),
                  h('text', {}, '，再生成电子合同'),
                ]),
                icon: 'none',
              })
            } else {
              uni.showToast({
                title: '合同更新成功',
                icon: 'none',
              })
              uni.$emit('refreshData')
              uni.navigateBack()
            }
          })
          .catch(() => {
            okLoading.value = false
          })
      }
    })
  }

  //   获取合同中信息
  const getContractDetail = (val) => {
    getContractDataAPI(val).then((res) => {
      form.value = res.result
      form.value.contractType = contractType.value
      form.value.id = contractId.value
      form.value.timeRange = [form.value.startTime, form.value.endTime]
      console.log(res.result, 'res.result')
      // // 更新取车门店
      // updateShortsiteConfig(form.value.siteId, form.value.siteName, 'site')
      // // 更新还车门店
      // updateShortsiteConfig(form.value.returnSiteId, form.value.returnSiteName, 'returnSite')
    })
  }
  onLoad((options) => {
    getContractDetail(options)
    contractType.value = Number(options.contractType)
    contractId.value = options.id
    // 车型选择完成
    uni.$on('carStock:selectCarOk', (carId, option, queryParam) => {
      console.log(option, 'option')
      form.value.carId = carId
      form.value.carLicenseNo = option.licenseNo
      form.value.carModelName = option.modelName

      // 记录弹窗queryParam
      platoonModelQueryParam.value = { ...queryParam }
    })
    // 上门送取车地址选择完成
    uni.$on('mapSelectSuccess', (info) => {
      console.log(info)
      // 处理选择地图后再次回到当前页，需要取得当前操作的类型（取车地址 or 还车地址）
      let mapSuccessType = uni.getStorageSync('showMapLnglatOperateType')
      if (mapSuccessType == 'site') {
        form.value.address = info.address
        form.value.longitude = info.longitude
        form.value.latitude = info.latitude
      } else {
        form.value.returnAddress = info.address
        form.value.returnLongitude = info.longitude
        form.value.returnLatitude = info.latitude
      }
      uni.removeStorageSync('showMapLnglatOperateType')
    })
    onUnload(() => {
      uni.$off('carStock:selectCarOk')
      uni.$off('mapSelectSuccess')
    })
  })
</script>
<style lang="less" scoped>
  .container {
    padding-bottom: 120rpx;
  }
  .alert-content {
    width: 100%;
    background: #e8f3ff;
    padding: 24rpx;
    margin-bottom: 24rpx;
    .alert-item {
      font-size: 24rpx;
      color: #1e1e1e;
      line-height: 44rpx;
      image {
        width: 32rpx;
        height: 32rpx;
        margin-right: 12rpx;
      }
    }
  }
  .memeber-type-form {
    /deep/ .ve-form-item__body__right {
      display: flex;
      align-items: center;
    }
  }
  .time-range-wrap {
    flex: 1;
    .quick-date-list {
      display: flex;
      justify-content: space-between;
      margin-bottom: 32rpx;
      .quick-date-item {
        height: 48rpx;
        line-height: 44rpx;
        border-radius: 4rpx 4rpx 4rpx 4rpx;
        opacity: 1;
        border: 2rpx solid #dadbdd;
        padding: 0 24rpx;

        font-size: 24rpx;
        color: #55585f;
        &.active {
          background: #e0edff;
          border: 2rpx solid #3072f6;
          font-weight: 600;
          color: #3072f6;
        }
      }
    }
  }
  .platoon-model {
    width: 100%;
    background: #f7f8fa;
    padding: 34rpx 24rpx;
    font-size: 30rpx;
    color: #191c27;
  }
  #footer-box {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #ffffff;
    z-index: 100;
    /deep/ .ve-button {
      padding: 0;
    }
  }
</style>
